import { WsAdapter } from '@nestjs/platform-ws'
import { MessageMappingProperties } from '@nestjs/websockets'
import { Observable, EMPTY } from 'rxjs'

export class ActionSocketAdapter extends WsAdapter {
  public bindMessageHandler(
    buffer: any,
    handlers: MessageMappingProperties[],
    transform: (data: any) => Observable<any>
  ): Observable<any> {
    try {
      const message = JSON.parse(buffer.data)
      const messageHandler = handlers.find(handler => handler.message === message.action)
      const { callback } = messageHandler
      return transform(callback(message.data, message.action))
    } catch {
      return EMPTY
    }
  }
}
